package com.main.shake;

import com.google.gson.Gson;
import com.main.common.Response;
import com.main.util.EncryptionUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;

@Aspect
@Component
public class EncryptionAspect {

    private static final Logger logger = LoggerFactory.getLogger(EncryptionAspect.class);

    @Around("@annotation(Encrypt)")
    public void encryptResponse(ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

        Object result = joinPoint.proceed();
        Gson gson = new Gson();
        String json = gson.toJson(result);

        try (OutputStream out = new BufferedOutputStream(response.getOutputStream())) {
            byte[] jsonData = json.getBytes("UTF-8");
            byte[] encryptedData = EncryptionUtil.encrypt(jsonData).getBytes();

            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentLength(encryptedData.length);

            out.write(encryptedData);
            out.flush();

            // 记录发送的百分比
                int length = encryptedData.length;
                for (int i = 0; i < length; i += 100) {
                    int percentage = (int) ((i * 100.0) / length);
                    logger.info("已发送 {}% 的数据", percentage);
                }
                logger.info("数据加密完成，已发送 {} 字节的数据", encryptedData.length);
        } catch (Exception e) {
            logger.error("加密过程中发生错误: {}", e.getMessage(), e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");

            String errorMessage = gson.toJson(Response.failure(HttpStatus.INTERNAL_SERVER_ERROR, "加密过程中发生错误"));
            try (OutputStream out = new BufferedOutputStream(response.getOutputStream())) {
                out.write(errorMessage.getBytes("UTF-8"));
                out.flush();
            }
        }
    }
}